package com.ggymm.browser;

import com.ggymm.browser.base.BrowserFrame;
import com.ggymm.browser.core.Config;
import com.ggymm.browser.dialog.DevToolsDialog;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.CefSettings;
import org.cef.OS;
import org.cef.browser.CefBrowser;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class FakeApplication extends BrowserFrame {

    private final CefClient client;

    FakeApplication(CefClient client) {
        this.client = client;
    }

    public static void main(String[] args) {
        Config.initDll();
        if (!CefApp.startup(args)) {
            System.out.println("Startup initialization failed!");
            return;
        }
        CefSettings settings = new CefSettings();
        settings.windowless_rendering_enabled = OS.isLinux();
        CefApp cefApp = CefApp.getInstance(settings);
        CefApp.CefVersion version = cefApp.getVersion();
        System.out.println("Using:\n" + version);
        final CefClient client = cefApp.createClient();
        FakeApplication app = new FakeApplication(client);
        app.createBrowser();
    }

    private void createBrowser() {
        // 设置浏览器
        CefBrowser browser = client.createBrowser("file:///./index.html", OS.isLinux(), false);

        // 设置标题
        setTitle("安全浏览器");
        JMenuBar menuBar = new JMenuBar();
        JMenu tools = new JMenu("工具");
        JMenuItem devtools = new JMenuItem("开发者工具");
        devtools.addActionListener(e -> {
            DevToolsDialog devToolsDlg = new DevToolsDialog(this, "开发者工具", browser);
            devToolsDlg.setVisible(true);
        });
        menuBar.add(tools.add(devtools));
        setJMenuBar(menuBar);

        // 页面
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.add(browser.getUIComponent(), BorderLayout.CENTER);
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
                CefApp.getInstance().dispose();
            }
        });
        setSize(1200, 800);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}
